package xyz.comfyz.web.commons.security.provider;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import xyz.comfyz.web.commons.security.model.Authentication;
import xyz.comfyz.web.commons.security.model.SecurityToken;
import xyz.comfyz.web.commons.security.support.SecurityContext;

/**
 * @author :    comfy
 * @date :      2018-05-12 16:04:49
 * @since :     1.8
 * <p>
 * 根据token获取用户
 */
@Component
public final class AuthenticationProvider {

    private final UserDetailsService userDetailsService;

    @Autowired
    public AuthenticationProvider(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    public Authentication authenticate(SecurityToken securityToken) {
        if (securityToken == null || !StringUtils.hasText(securityToken.getUserId()))
            return null;

        Authentication token = SecurityContext.authentication();

        if (token == null)
            token = userDetailsService.loadUser(securityToken.getUserId());

        if (token != null) {
            SecurityContext.set(token);
        }
        return token;
    }

}
